<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>节流</title>
	<style>
		#box{
			width:200px;
			height:200px;
			background:blue;
			font-size:30px;
			color:#fff;
			text-align: center;
			line-height: 200px;
			user-select: none;
		}
	</style>
</head>
<body>
	<div id="box"></div>
	<script type="text/javascript">
		// 持续触发事件时，保证一定时间段内，只触发一次事件处理函数；也就是，固定时间段内，一个动作只执行一次
		// 适用场景 resize  scroll mousemove mousehover 懒加载、滚动加载
		let num = 0;
		let content = document.getElementById('box');
		function count(){
			num++
			content.innerHTML=num
		}
		// 1、节流 ------ 时间戳
		// 时间戳方法会立即执行
		function throttle(fn, wait){
			let last = 0;
			return function(){
				const now = Date.now();
				if(now - last >= wait){
					last = now;
					fn.apply(this, arguments)
				}
			}
		}
		// 2、节流 ------ 定时器
		// 定时器方法会延迟执行，最后一步也会延迟执行
		function throttle1(fn, wait){
			let timer = null;
			return function(){
				if(!timer){
					timer = setTimeout(() => {
						fn.apply(this, arguments);
						timer = null
					}, wait)
				}
			}
		}
		// 3、节流 ------ 根据剩余时间，判断是否立即执行/延迟执行
		function throttle2(fn, wait){
			let timer,startTime=Date.now();
			return function(){
				const currentTime = Date.now();
				const remain = wait - (currentTime - startTime); // 获取剩余时间
				clearTimeout(timer)
				if(remain <= 0){
					fn.apply(this, arguments);
					startTime = Date.now()
				} else{
					timer = setTimeout(fn, remain)
				}
			}
		}
		content.onclick = throttle2(count, 2000)
	</script>
</body>
</html>